package com.mydomain.debtbook;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import com.mydomain.debtbook.ViewDebtActivity.MyExpandableNameListAdapter;

import android.app.Activity;
import android.app.ExpandableListActivity;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CursorTreeAdapter;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView.OnChildClickListener;

public class ResolveActivity extends Activity {

	private DebtAdapter debtAdapter;
	private Cursor debtNameCursor;
	private SimpleCursorAdapter cursorAdapter;
	private SimpleCursorAdapter cursorAdapterSolution;
	private DecimalFormat myformatShort;
	private DecimalFormat myformatLong;
	private String childName;
	private ExpandableListAdapter listAdapter;
	private ExpandableListView expandListView;
	private Cursor groupCursor;
	private ListView debtNamesList;
	private ArrayList<Double> resolveData;
	private BiDiMap<String, Double> BiDiResolve;
	private ArrayList<HashMap<String, String>> hashSolution;
	private ListView solutionListView;
	private boolean solutionFlag;
	private solutionAdapter mySolutionAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		debtAdapter = ((debtBookApplication) this.getApplication())
				.getDatabaseAdapter();
		setContentView(R.layout.resolve_page);
		myformatShort = new DecimalFormat("###,###.00");
		myformatLong = new DecimalFormat("###,###");

		solutionFlag = false;
		solutionListView = (ListView) findViewById(R.id.rp_listResolveSolution);
		expandListView = (ExpandableListView) findViewById(R.id.rp_listContactSum);
		debtNamesList = (ListView) findViewById(R.id.rp_listContacts);
		hashSolution = new ArrayList<HashMap<String, String>>();
		mySolutionAdapter = new solutionAdapter(this,
				R.layout.list_resolve_solution, hashSolution);
		initExpandableNameList();
		showDebtNames();
		
	}

	private void initExpandableNameList() {
		groupCursor = debtAdapter.getGroupResolveDebtSum();



		listAdapter = new MyExpandableNameListAdapter(groupCursor, this,
				R.layout.debt_group_row, R.layout.resolve_child_row,
				new String[] { DebtAdapter._NAME, DebtAdapter._DEBTAMOUNT },
				new int[] { R.id.gr_name, R.id.gr_debtamount }, new String[] {
						DebtAdapter._NAME, DebtAdapter._DEBTAMOUNT },
				new int[] { R.id.rcr_name, R.id.rcr_debtamount });

		expandListView.setAdapter(listAdapter);

	}

	private void showDebtNames() {
		debtNameCursor = debtAdapter.getAllItemCursor(DebtAdapter.DB_TB_NAMES);
		if (debtNameCursor != null) {
			startManagingCursor(debtNameCursor);
		}

		cursorAdapter = new debtNameListAdapter(this,
				android.R.layout.simple_list_item_1, debtNameCursor,
				new String[] { DebtAdapter._ITEM },
				new int[] { android.R.id.text1 });

		debtNamesList.setAdapter(cursorAdapter);

		debtNamesList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				boolean insert;
				String name = debtNameCursor.getString(debtNameCursor
						.getColumnIndexOrThrow(DebtAdapter._ITEM));

				ContentValues resolveValues = new ContentValues();
				resolveValues.put(DebtAdapter._NAME, name);
				insert = debtAdapter.insertOrDeleteResolve(name, resolveValues);
				groupCursor = debtAdapter.getGroupResolveDebtSum();

				refreshSolution();
				cursorAdapter.notifyDataSetChanged();
				((SimpleCursorTreeAdapter) listAdapter).getCursor().requery();

				mySolutionAdapter = new solutionAdapter(getBaseContext(),
						R.layout.list_resolve_solution, hashSolution);
				solutionListView.setAdapter(mySolutionAdapter);
			}
		});
	}

	public class debtNameListAdapter extends SimpleCursorAdapter {

		private LayoutInflater mInflater;
		private Context context;
		private TextView nameTv;
		private String[] myFrom;

		public debtNameListAdapter(Context context, int layout, Cursor cursor,
				String[] from, int[] to) {

			super(context, layout, cursor, from, to);
			mInflater = LayoutInflater.from(context);
			this.context = context;
			myFrom = from;
		}

		@Override
		public void bindView(View view, Context context, Cursor c) {
			int nameCol = c.getColumnIndexOrThrow(myFrom[0]);

			String name = c.getString(nameCol);

			TextView nameTv = (TextView) view.findViewById(android.R.id.text1);

			nameTv.setText(name);
			if (debtAdapter.existResolve(name)) {
				nameTv.setTextColor(Color.parseColor("#778899"));
			} else {
				nameTv.setTextColor(Color.WHITE);
			}

		}
	}

	public class MyExpandableNameListAdapter extends SimpleCursorTreeAdapter {

		public MyExpandableNameListAdapter(Cursor cursor, Context context,
				int groupLayout, int childLayout, String[] groupFrom,
				int[] groupTo, String[] childrenFrom, int[] childrenTo) {
			super(context, cursor, groupLayout, groupFrom, groupTo,
					childLayout, childrenFrom, childrenTo);
		}

		@Override
		protected Cursor getChildrenCursor(Cursor groupCursor) {

			childName = groupCursor.getString(groupCursor
					.getColumnIndex(DebtAdapter._NAME));

			Cursor childCursor = debtAdapter.getChildResolveDebtSum(childName);

			return childCursor;

		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {

			View view = super.getGroupView(groupPosition, isExpanded,
					convertView, parent);
			TextView parentViewDebt = (TextView) view
					.findViewById(R.id.gr_debtamount);
			TextView parentViewDollar = (TextView) view
					.findViewById(R.id.gr_dollarsign);

			double debt = Double.parseDouble(parentViewDebt.getText()
					.toString());
			if (debt == 0) {
				parentViewDebt.setTextColor(Color.GRAY);
				parentViewDollar.setTextColor(Color.GRAY);
			} else if (debt > 0) {
				parentViewDebt.setTextColor(Color.GREEN);
				parentViewDollar.setTextColor(Color.GREEN);
			} else {
				parentViewDebt.setTextColor(Color.RED);
				parentViewDollar.setTextColor(Color.RED);
			}

			if (Math.abs(debt) > 999999) {

				parentViewDebt.setText(myformatLong.format(debt)
						.substring(0, 6) + "...");

			} else if (Math.abs(debt) > 9999) {
				parentViewDebt.setText(myformatLong.format(debt));

			} else {
				parentViewDebt.setText(myformatShort.format(debt));
			}

			return view;

		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {

			View view = super.getChildView(groupPosition, childPosition,
					isLastChild, convertView, parent);

			TextView childViewDebt = (TextView) view
					.findViewById(R.id.rcr_debtamount);
			TextView childViewDollar = (TextView) view
					.findViewById(R.id.rcr_dollarsign);

			double debt = Double
					.parseDouble(childViewDebt.getText().toString());

			if (debt == 0) {
				childViewDebt.setTextColor(Color.GRAY);
				childViewDollar.setTextColor(Color.GRAY);

			} else if (debt > 0) {
				childViewDebt.setTextColor(Color.GREEN);
				childViewDollar.setTextColor(Color.GREEN);

			} else {
				childViewDebt.setTextColor(Color.RED);
				childViewDollar.setTextColor(Color.RED);

			}

			if (Math.abs(debt) > 999999) {

				childViewDebt.setText(myformatLong.format(debt).substring(0, 6)
						+ "...");

			} else if (Math.abs(debt) > 9999) {
				childViewDebt.setText(myformatLong.format(debt));

			} else {
				childViewDebt.setText(myformatShort.format(debt));
			}

			return view;

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_resolve, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mr_resolve:
			debtAdapter.clearResolve();
			return true;
		case R.id.mr_switch:
			switchView();
			return true;
		}
		return false;
	}

	private void switchView() {

		if (solutionFlag) {

			solutionFlag = false;
			expandListView.setVisibility(View.VISIBLE);
			solutionListView.setVisibility(View.GONE);
		} else {
			solutionFlag = true;
			refreshSolution();
			mySolutionAdapter = new solutionAdapter(this,
					R.layout.list_resolve_solution, hashSolution);

			solutionListView.setAdapter(mySolutionAdapter);
			expandListView.setVisibility(View.GONE);
			solutionListView.setVisibility(View.VISIBLE);

		}

	}

	private void refreshSolution() {

		if (hashSolution == null) {
			hashSolution = new ArrayList<HashMap<String, String>>();
		}

		if (mySolutionAdapter == null) {
			mySolutionAdapter = new solutionAdapter(this,
					R.layout.list_resolve_solution, hashSolution);
		}

		if (groupCursor.getCount() > 1 && solutionFlag) {
			int nameCol = groupCursor.getColumnIndexOrThrow(DebtAdapter._NAME);
			int debtCol = groupCursor
					.getColumnIndexOrThrow(DebtAdapter._DEBTAMOUNT);
			double minDebt;
			double maxDebt;
			double debtSum;
			double maxNewDebt;
			String maxPerson;
			String minPerson;

			BiDiResolve = new BiDiMap<String, Double>();
			hashSolution = new ArrayList<HashMap<String, String>>();

			for (groupCursor.moveToFirst(); !groupCursor.isAfterLast(); groupCursor
					.moveToNext()) {

				BiDiResolve.put(groupCursor.getString(nameCol), ((double) Math
						.round(groupCursor.getDouble(debtCol) * 100)) / 100);

			}

			while (BiDiResolve.size() > 0) {

				maxDebt = Collections.max((Collection<Double>) BiDiResolve
						.values());
				minDebt = Collections.min((Collection<Double>) BiDiResolve
						.values());

				maxPerson = BiDiResolve.getKey(maxDebt);
				minPerson = BiDiResolve.getKey(minDebt);

				HashMap<String, String> mp = new HashMap<String, String>();
				mp.put("lender", minPerson);
				mp.put("borrower", maxPerson);
				mp.put("debt",
						String.valueOf(Math.min(Math.abs(maxDebt),
								Math.abs(minDebt))));

				hashSolution.add(mp);
				BiDiResolve.removeByValue(minDebt);

				if ((double) Math.round(Math.max((maxDebt + minDebt) * 100, 0)) / 100 <= 0) {
					BiDiResolve.removeByKey(maxPerson);
				} else {
					BiDiResolve.put(maxPerson,
							Double.valueOf((double) Math.round(Math.max(
									(maxDebt + minDebt) * 100, 0)) / 100));

				}

				if ((double) Math.round(Math.min((maxDebt + minDebt) * 100, 0)) / 100 >= 0) {
					BiDiResolve.removeByKey(minPerson);
				} else {

					BiDiResolve.put(minPerson,
							Double.valueOf((double) Math.round(Math.min(
									(maxDebt + minDebt) * 100, 0)) / 100));

				}

				BiDiResolve.syncKeyValue();

			}


		} else {
			hashSolution.clear();
		}
	}

	private class solutionAdapter extends ArrayAdapter<HashMap<String, String>> {

		private ArrayList<HashMap<String, String>> solutionName;
		private LayoutInflater mInflater;

		public solutionAdapter(Context context, int textViewResourceId,
				ArrayList<HashMap<String, String>> items) {
			super(context, textViewResourceId, items);
			mInflater = LayoutInflater.from(context);
			this.solutionName = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_resolve_solution,
						null);
				holder = new ViewHolder();

				holder.borrower = (TextView) convertView
						.findViewById(R.id.lrs_nameBorrower);
				holder.lender = (TextView) convertView
						.findViewById(R.id.lrs_nameLender);
				holder.debt = (TextView) convertView
						.findViewById(R.id.lrs_debtAmount);

				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}


			holder.lender.setText(hashSolution.get(position).get("lender"));
			holder.borrower.setText(hashSolution.get(position).get("borrower"));
			holder.debt.setText(hashSolution.get(position).get("debt"));
			return convertView;

		}

		class ViewHolder {
			TextView borrower;
			TextView lender;
			TextView debt;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		((SimpleCursorTreeAdapter) listAdapter).getCursor().requery();
	}
}
